package com.example.poemtest.mine;

/**
 * 诗词道具页面
 */

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.poemtest.Activity.BottomNavigationViewActivity;
import com.example.poemtest.Activity.LoginActivity;
import com.example.poemtest.R;
import com.example.poemtest.entity.PropInfoBean;
import com.example.poemtest.entity.UserInfoBean;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PoetryPropActivity extends AppCompatActivity {

    private GridView gridView;
    private List<Prop> propList = new ArrayList<>();
    private PropAdapter propAdapter;
    private ImageView back;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            int flag = msg.arg1;
            if (flag == 0) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
//                    PropInfoBean propInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PropInfoBean.class);
//                    List<PropInfoBean.PropInfo> list = propInfoBean.getData();
//                    for (PropInfoBean.PropInfo propInfo : list) {
//                        Constant.propInfoList.add(propInfo);
//                    }
//                    for (PropInfoBean.PropInfo propInfo : Constant.propInfoList) {
//                        Log.e("收到的道具数据",propInfo.toString());
//                    }
                    } else {
                        Toast.makeText(PoetryPropActivity.this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 1) {
                Log.e("flag",flag + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PropInfoBean propInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PropInfoBean.class);
                        List<PropInfoBean.PropInfo> list = propInfoBean.getData();
                        if (Constant.myPropList.size() != 0) {
                            Constant.myPropList.clear();
                        }
                        for (PropInfoBean.PropInfo propInfo : list) {
                            Constant.myPropList.add(propInfo);
                        }
                        for (PropInfoBean.PropInfo propInfo : Constant.myPropList) {
                            Log.e("收到的道具数据",propInfo.toString());
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtil.getInstance().fullScreen(this,true);
        setContentView(R.layout.activity_poetry_prop);
        //绑定控件对象
        initView();
        //设置数据源
//        setData();
        //初始化适配器
        propAdapter = new PropAdapter(
                this,
                Constant.propInfoList,
                R.layout.layout_prop_item
        );
        //为GridView绑定适配器
        gridView.setAdapter(propAdapter);
//        propAdapter.setOnInnerItemOnClickListener(this);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击了某个道具的兑换按钮后
                //1.判断当前积分是否大于道具所需的积分，购买成功
                if (Constant.userGrade > Constant.propInfoList.get(position).getPropNum() || Constant.userGrade == Constant.propInfoList.get(position).getPropNum()) {
                    //设置网络连接，修改后台信息，加入道具，减少积分
                    getCoon(Constant.propInfoList.get(position).getPropId());
                    getCoon1();
//                    Constant.userGrade -= propList.get(position).getPropNum();
                    Log.e("积分",Constant.userGrade + "");
                } else {
                    //如果积分不够，提示当前积分不足，请先去学习获取积分
                    Toast.makeText(PoetryPropActivity.this,"当前积分不足，请先去学习获取积分！",Toast.LENGTH_SHORT).show();
                }
            }
        });
        //返回到我的道具页面
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PoetryPropActivity.this,MyPropActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置数据源
     */
    private void setData() {
        Prop prop1 = new Prop();
        prop1.setPropImg("http://hn-bkt.clouddn.com/img/prop1.png");
        prop1.setPropName("毛笔");
        prop1.setPropNum(10);
        propList.add(prop1);
        Prop prop2 = new Prop();
        prop2.setPropImg("http://hn-bkt.clouddn.com/img/prop2.png");
        prop2.setPropName("葫芦");
        prop2.setPropNum(22);
        propList.add(prop2);
        Prop prop3 = new Prop();
        prop3.setPropImg("http://hn-bkt.clouddn.com/img/prop3.png");
        prop3.setPropName("环扣");
        prop3.setPropNum(15);
        propList.add(prop3);
        Prop prop4 = new Prop();
        prop4.setPropImg("http://hn-bkt.clouddn.com/img/prop4.png");
        prop4.setPropName("诗经");
        prop4.setPropNum(6);
        propList.add(prop4);
        Prop prop5 = new Prop();
        prop5.setPropImg("http://hn-bkt.clouddn.com/img/prop5.png");
        prop5.setPropName("酒");
        prop5.setPropNum(20);
        propList.add(prop5);
        Prop prop6 = new Prop();
        prop6.setPropImg("http://hn-bkt.clouddn.com/img/prop6.png");
        prop6.setPropName("灯笼");
        prop6.setPropNum(7);
        propList.add(prop6);
        Prop prop7 = new Prop();
        prop7.setPropImg("http://hn-bkt.clouddn.com/img/prop7.png");
        prop7.setPropName("折扇");
        prop7.setPropNum(17);
        propList.add(prop7);
        Prop prop8 = new Prop();
        prop8.setPropImg("http://hn-bkt.clouddn.com/img/prop8.png");
        prop8.setPropName("卷轴");
        prop8.setPropNum(4);
        propList.add(prop8);
        Prop prop9 = new Prop();
        prop9.setPropImg("http://hn-bkt.clouddn.com/img/prop9.png");
        prop9.setPropName("诗书");
        prop9.setPropNum(13);
        propList.add(prop9);
    }

    /**
     * 绑定控件对象
     */
    private void initView() {
        back = findViewById(R.id.setup_safe_to_mine);
        gridView = findViewById(R.id.prop_grid_view);
    }

    /**
     * 获取网络连接
     */
    private void getCoon(int propId){
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/propToUser/add?userId=" + Constant.userId + "&propId=" + propId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 0;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取网络连接，刷新我的道具列表
     */
    private void getCoon1(){
        Log.e("刷新道具数据","刷新数据");
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/propInfo/findPropByUserId?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 1;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}